package com.springcloud.zull.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wfh
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.springcloud.zull.aop.LogAnnotation)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        log.info("请求地址:" + request.getRequestURL());
        log.info("请求IP:" + request.getRemoteAddr());
        long startTime = System.currentTimeMillis();
        log.info("请求时间:" + simpleDateFormat.format(new Date(startTime)));
        Object object;
        try {

            object = pjp.proceed();
            log.info(pjp.getSignature() + "耗时:" + (System.currentTimeMillis() - startTime));
            return object;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
